//
//  ViewController.swift
//  ElectrickService
//
//  Created by David on 2017/6/15.
//  Copyright © 2017年 David. All rights reserved.
//

import Cocoa

class ViewController: NSViewController {

    @IBOutlet var msgLabel: NSTextField!
    @IBOutlet var unameText: NSTextField!
    @IBOutlet var pswText: NSSecureTextField!
    @IBOutlet var verifyText: NSTextField!
    @IBOutlet var codeImgBtn: NSButton!
    @IBOutlet var loginBtn: NSButton!
    @IBOutlet var spinner: NSProgressIndicator!
    
    var ebService: EBService!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        codeImgBtn.layer?.backgroundColor = NSColor.white.cgColor
        
        spinner.isDisplayedWhenStopped = false
        
        ebService = (NSApplication.shared().delegate as! AppDelegate).ebService
        
    }

    @IBAction func codeImgBtnClick(_ sender: Any) {
        setCodeLoadingState(true)
        ebService.loadCode(true)
        
    }
    @IBAction func loginBtnClick(_ sender: Any) {
        print("loginBtnClick")
        
        if unameText.stringValue == "" {
            unameText.becomeFirstResponder()
            return
        }
        
        if pswText.stringValue == "" {
            pswText.becomeFirstResponder()
            return
        }
        
        if verifyText.stringValue == "" {
            verifyText.becomeFirstResponder()
            return
        }
        setLoadingState(true)
        ebService.doLogin(username: unameText.stringValue, psw: pswText.stringValue, code: verifyText.stringValue)
        
        
        
    }
    
    func setLoadingState(_ state: Bool){
        if state {
            spinner.startAnimation(spinner)
        }else{
            spinner.stopAnimation(spinner)
        }
        
        unameText.isEnabled = !state
        pswText.isEnabled = !state
        verifyText.isEnabled = !state
        codeImgBtn.isEnabled = !state
        loginBtn.isEnabled = !state
    }
    
    func setCodeLoadingState(_ state: Bool){
        if state {
            codeImgBtn.image = nil
            verifyText.stringValue = ""
        }
        verifyText.isEnabled = !state
        codeImgBtn.isEnabled = !state
    }
    
    @IBAction func quitBtnClick(_ sender: Any) {
        exit(0)
    }
    override var representedObject: Any? {
        didSet {
        // Update the view, if already loaded.
        }
    }


}

